<template>
  <div class="content">
    <div class="scroll-view-box">
      <el-form inline :model="addDiscountRuleForm" :rules="addDiscountRules" ref="addDiscountRuleForm"
        label-position="top">
        <el-form-item label="审批类型" prop="type">
          <el-radio-group @change="typeChangeFunc" v-model="addDiscountRuleForm.type" class="input-width">
            <el-radio :label="1">签约优惠</el-radio>
            <el-radio :label="2">结算优惠</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="项目名称" prop="project_id">
          <el-select filterable @change="projectChangeFunc" clearable class="input-width"
            v-model="addDiscountRuleForm.project_id" placeholder="">
            <el-option v-for="(item, index) in projectList" :key="index" :label="item.project_name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="addDiscountRuleForm.type == 1 ? '预算报价金额' : '结算报价金额'" prop="budget_quotation_amount">
          <el-input disabled clearable v-input-limit="2" class="input-width"
            v-model="addDiscountRuleForm.budget_quotation_amount">
            <span slot="suffix">元</span>
          </el-input>
        </el-form-item>
        <el-form-item :label="addDiscountRuleForm.type == 1 ? '预计签约金额' : '预计结算金额'" prop="expected_signing_amount">
          <el-input @change="JSpriceFunc" clearable v-input-limit="2" class="input-width"
            v-model="addDiscountRuleForm.expected_signing_amount">
            <span slot="suffix">元</span>
          </el-input>
        </el-form-item>
        <el-form-item label="成本金额" prop="cost_amount">
          <el-input @change="JSpriceFunc" clearable v-input-limit="2" class="input-width"
            v-model="addDiscountRuleForm.cost_amount">
            <span slot="suffix">元</span>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠金额" prop="discount_amount">
          <el-input disabled clearable v-input-limit="2" class="input-width"
            v-model="addDiscountRuleForm.discount_amount">
            <span slot="suffix">元</span>
          </el-input>
        </el-form-item>
        <el-form-item clearable label="优惠后利润金额" prop="remaining_profit_amount">
          <el-input disabled v-input-limit="2" class="input-width"
            v-model="addDiscountRuleForm.remaining_profit_amount">
            <span slot="suffix">元</span>
          </el-input>
        </el-form-item>
        <el-form-item clearable label="优惠后成本利润率" prop="remaining_cost_profit_ratio">
          <el-input disabled v-input-limit="2" class="input-width"
            v-model="addDiscountRuleForm.remaining_cost_profit_ratio">
            <span slot="suffix">%</span>
          </el-input>
        </el-form-item>
        <el-form-item clearable label="优惠前利润金额" prop="profit_amount">
          <el-input disabled v-input-limit="2" class="input-width" v-model="addDiscountRuleForm.profit_amount">
            <span slot="suffix">元</span>
          </el-input>
        </el-form-item>
        <el-form-item clearable label="优惠前成本利润率" prop="cost_profit_ratio">
          <el-input disabled v-input-limit="2" class="input-width" v-model="addDiscountRuleForm.cost_profit_ratio">
            <span slot="suffix">%</span>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <span>
          <el-button type="primary" @click="dkbjSubmit('addDiscountRuleForm')" :disabled="diaLoading"
            :loading="diaLoading">提交</el-button>
          <el-button @click="dkbjCancel('addDiscountRuleForm')">关闭</el-button>
        </span>
      </div>
    </div>
  </div>
</template>
<script>
import common from "@/api/common";
import discountApi from "@/api/discountApi";

export default {
  name: "addDiscount",
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.addDiscountRuleForm.type == 1 ? '输入预计报价金额' : '输入预计结算金额'))
      } else {
        callback()
      }
    }
    return {
      addDiscountRuleForm: {
        project_id: "",
        type: 1,
        cost_amount: "",
        budget_quotation_amount: "",
        expected_signing_amount: "",
        discount_amount: "",
        remaining_profit_amount: "",
        remaining_cost_profit_ratio: "",
        profit_amount: "",
        cost_profit_ratio: "",
      },
      addDiscountRules: {
        project_id: [
          { required: true, message: "请选择项目", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择审批类型", trigger: "change" },
        ],
        budget_quotation_amount: [
          { required: true, message: "输入预算报价金额", trigger: "change" },
        ],
        expected_signing_amount: [
          { required: true, trigger: "change", validator: validatePass },
        ],
        discount_amount: [
          { required: true, message: "输入优惠金额", trigger: "change" },
        ],
        remaining_profit_amount: [
          { required: true, message: "输入优惠后利润金额", trigger: "change" },
        ],
        remaining_cost_profit_ratio: [
          { required: true, message: "输入优惠后成本利润率", trigger: "change" },
        ],
        profit_amount: [
          { required: true, message: "输入优惠前利润金额", trigger: "change" },
        ],
        cost_profit_ratio: [
          { required: true, message: "输入优惠前成本利润率", trigger: "change" },
        ],
        cost_amount: [
          { required: true, message: "输入成本金额", trigger: "change" },
        ],
      },
      diaLoading: false,
      projectList: [],
      projectDetail: ""
    };
  },
  watch: {},
  computed: {},
  mounted() {
    this.selectProjectList({
      less_status: [1105],
      greater_status: [1092]
    });
  },
  methods: {
    // 签约优惠、结算优惠切换
    typeChangeFunc(type) {
      if (type == 1) {
        this.selectProjectList({
          less_status: [1105],
          greater_status: [1092]
        });
      } else {
        this.selectProjectList({
          greater_status: [1138]
        });
      }
      this.addDiscountRuleForm = {
        project_id: "",
        type,
        cost_amount: "",
        budget_quotation_amount: "",
        expected_signing_amount: "",
        discount_amount: "",
        remaining_profit_amount: "",
        remaining_cost_profit_ratio: "",
        profit_amount: "",
        cost_profit_ratio: "",
      }
      this.$nextTick(() => {
        this.$refs.addDiscountRuleForm.clearValidate();
      })
    },
    // 输入预计签约金额后进行计算
    JSpriceFunc(val) {
      let { expected_signing_amount, budget_quotation_amount } = this.addDiscountRuleForm;
      if (val && typeof val === 'number' && !isNaN(val)) return;
      // 优惠金额 = 预算报价-预计签约金额
      let discount_amount = Number(budget_quotation_amount) - Number(expected_signing_amount);
      this.addDiscountRuleForm.discount_amount = discount_amount.toFixed(2);
      this.$nextTick(() => {
        this.mathFunc();
      })
    },
    // 金额计算
    // ------ NEW CODE ----------
    // 添加辅助计算函数
    calculateProfitRatio(numerator, denominator) {
      if (Number(denominator) === 0) return 0;
      return (Number(numerator) / Number(denominator)) * 100;
    },

    calculateTotalCost(baseCost, procurementCost, centralizedCost, taxes = 0) {
      return Number(baseCost) + Number(procurementCost) + Number(centralizedCost) + Number(taxes);
    },
    // 重构后的mathFunc方法
    mathFunc() {
      let projectDetail = this.projectDetail;
      let { discount_amount } = this.addDiscountRuleForm;

      // 签约优惠
      if (this.addDiscountRuleForm.type == 1) {
        // 优惠前成本利润率
        if (String(projectDetail.system_quotation) && String(projectDetail.cost_amount)) {
          const profit = Number(projectDetail.system_quotation) - Number(projectDetail.cost_amount);
          this.addDiscountRuleForm.cost_profit_ratio = this.calculateProfitRatio(profit, projectDetail.cost_amount).toFixed(2);
        }

        // 优惠后利润金额计算
        if (String(this.addDiscountRuleForm.expected_signing_amount) && String(this.addDiscountRuleForm.cost_amount)) {
          const totalCost = this.calculateTotalCost(
            this.addDiscountRuleForm.cost_amount,
            projectDetail.procurement_cost,
            projectDetail.centralized_procurement_cost
          );
          this.addDiscountRuleForm.remaining_profit_amount = (Number(this.addDiscountRuleForm.expected_signing_amount) - totalCost).toFixed(2);
        }

        // 优惠后成本利润率
        if (String(projectDetail.procurement_cost) && String(projectDetail.centralized_procurement_cost) && String(this.addDiscountRuleForm.cost_amount)) {
          const totalCost = this.calculateTotalCost(
            this.addDiscountRuleForm.cost_amount,
            projectDetail.procurement_cost,
            projectDetail.centralized_procurement_cost,
            projectDetail.quotation_taxes
          );
          const profit = Number(this.addDiscountRuleForm.budget_quotation_amount) - totalCost - Number(discount_amount);
          this.addDiscountRuleForm.remaining_cost_profit_ratio = this.calculateProfitRatio(profit, totalCost).toFixed(2);
        }
      } else {
        // 结算优惠逻辑...
        // 优惠后利润金额计算
        // （【利润金额】-【优惠金额】）    ---弃用
        // 优惠审批页面【预计结算金额】-（优惠审批界面填写的成本金额+结算的现场采购成本+结算的公司集采成本）    ---现用  2025-9-19
        if (String(this.addDiscountRuleForm.cost_amount) && String(this.addDiscountRuleForm.expected_signing_amount)) {
          const remaining_profit_amount = this.calculateTotalCost(
            projectDetail.final_procurement_cost,
            projectDetail.final_centralized_procurement_cost,
            this.addDiscountRuleForm.cost_amount
          );
          this.addDiscountRuleForm.remaining_profit_amount = Number(this.addDiscountRuleForm.expected_signing_amount) - Number(remaining_profit_amount);
        }
        // 优惠后成本利润率
        // （结算报价金额-结算成本金额-优惠金额）/结算成本金额*100%    ---弃用
        // 【结算报价金额-（优惠审批界面填写的成本金额+结算的现场采购成本+结算的公司集采成本）-优惠金额）】/成本金额(输入成本+结算现场采购+结算公司采集)*100%     ---现用  2025-9-19
        if (String(this.addDiscountRuleForm.budget_quotation_amount) && String(this.addDiscountRuleForm.discount_amount) && String(this.addDiscountRuleForm.cost_amount)) {
          let remaining_cost_profit_ratio = '';
          const cost_amount = this.calculateTotalCost(
            projectDetail.final_procurement_cost,
            projectDetail.final_centralized_procurement_cost,
            this.addDiscountRuleForm.cost_amount
          );
          remaining_cost_profit_ratio = Number(cost_amount) + Number(this.addDiscountRuleForm.discount_amount);
          remaining_cost_profit_ratio = Number(this.addDiscountRuleForm.budget_quotation_amount) - Number(remaining_cost_profit_ratio);
          remaining_cost_profit_ratio = Number(remaining_cost_profit_ratio) / Number(cost_amount);
          this.addDiscountRuleForm.remaining_cost_profit_ratio = (Number(remaining_cost_profit_ratio) * 100).toFixed(2);
        }
      }
    },
    // --------------------------
    // 选择项目
    projectChangeFunc(project_id) {
      console.log(project_id)
      if (!project_id) {
        this.addDiscountRuleForm = {
          project_id: '',
          type: this.addDiscountRuleForm.type,
          budget_quotation_amount: "",
          expected_signing_amount: "",
          discount_amount: "",
          remaining_profit_amount: "",
          remaining_cost_profit_ratio: "",
          profit_amount: "",
          cost_profit_ratio: "",
        }
        return;
      }
      common.selectProjectDetails({
        project_id
      }).then(res => {
        console.log(res, "项目详情")
        if (res.code == 200) {
          this.projectDetail = res.data;
          if (this.addDiscountRuleForm.type == 1) {
            this.addDiscountRuleForm.budget_quotation_amount = res.data.system_quotation;//预算报价金额
            this.addDiscountRuleForm.expected_signing_amount = res.data.quotation_amount || '';//预算签约金额
            this.addDiscountRuleForm.discount_amount = res.data.discount_amount;//优惠金额
            this.addDiscountRuleForm.profit_amount = res.data.quotation_profit_amount;//优惠前利润金额
          } else {
            if (!res.data.settlement_cost_amount || res.data.settlement_cost_amount == '0') {
              this.$message({
                type: 'warning',
                message: '该项目未结算，无法发起优惠审批'
              })
              return;
            }
            this.addDiscountRuleForm.budget_quotation_amount = res.data.settlement_amount;//结算报价金额*
            // this.addDiscountRuleForm.expected_signing_amount = res.data.settlement_quotation_amount || '';//预计结算金额“
            // let discount_amount = Number(
            //   math.format(
            //     math.subtract(
            //       math.bignumber(res.data.settlement_amount),
            //       math.bignumber(res.data.settlement_quotation_amount),
            //     )
            //   )
            // )
            // this.addDiscountRuleForm.discount_amount = discount_amount;//优惠金额
            this.addDiscountRuleForm.profit_amount = res.data.profit_amount;//优惠前利润金额
            this.addDiscountRuleForm.cost_profit_ratio = res.data.settlement_profit_margin;//优惠前利润率
          }

          // 计算金额
          this.mathFunc();
        }
      })
    },
    // 项目列表
    selectProjectList(obj) {
      common.selectProjectList(obj).then(res => {
        console.log(res, "项目列表")
        if (res.code == 200) {
          this.projectList = res.data;
        }
      })
    },
    // 提交优惠审批
    dkbjCancel(formName) {
      this.$goBackTab(this, () => {
        this.$router.push({
          path: '/discountApproval'
        })
      });
    },
    dkbjSubmit(formName) {
      let addDiscountRuleForm = this.addDiscountRuleForm;
      console.log(addDiscountRuleForm, "参数");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addDiscount({
            project_id: addDiscountRuleForm.project_id,
            type: addDiscountRuleForm.type,
            budget_quotation_amount: addDiscountRuleForm.budget_quotation_amount,
            expected_signing_amount: addDiscountRuleForm.expected_signing_amount,
            discount_amount: addDiscountRuleForm.discount_amount,
            remaining_profit_amount: addDiscountRuleForm.remaining_profit_amount,
            remaining_cost_profit_ratio: addDiscountRuleForm.remaining_cost_profit_ratio,
            profit_amount: addDiscountRuleForm.profit_amount,
            cost_profit_ratio: addDiscountRuleForm.cost_profit_ratio,
            cost_amount: addDiscountRuleForm.cost_amount
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 发起优惠审批
    addDiscount(obj) {
      this.diaLoading = true;
      discountApi.addDiscount(obj).then(res => {
        console.log(res, "发起优惠审批")
        this.diaLoading = false;
        if (res.code == 200) {
          this.dkbjCancel();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
  },
};
</script>
<style lang="scss" scoped>
// @import "@/styles/dialogPageCss.scss";
@import "@/styles/addPage.scss";
</style>